package com.Policing.Scrap;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import android.util.Base64;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Since_case.Since_case;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.demo.WaveSwipeRefreshLayout;
import com.Policing.Adapter.Addrepairs_Adapter;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.bean.AddRepairs_bean;
import com.Policing.bean.Property_bean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/3/18.
 */

public class Scrap_dispose extends Activity implements OnDismissListener {
    private ListView lv_poperty;
    private TextView title_text;
    private ImageView fh;
    private List<AddRepairs_bean> data = new ArrayList<>();
    WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
    private String repairsId;
    private String datas,status="状态";
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private String url="http://"+ Ip_Set.IP+"/api/scrapQueryById";
    private String eliminate_url="http://"+ Ip_Set.IP+"/api/scrapDelete";
    private String url_up="http://"+ Ip_Set.IP+"/api/scrapDetailDelete";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.repairs_property);
        inview();
        load();
    }

    private void inview() {
        fh = (ImageView) findViewById(R.id.fh);
        fh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //为啥一定要上传附件才能报废呀
                if (status.equals("待上传附件")) {
                new AlertView(" 提示！", "退出后，未上传附件的将不申请报废", "取消",new String[]{"确定"}, null, Scrap_dispose.this, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){
                            eliminate();
                        }
                        if (position==-1){

                        }

                    }
                }).setCancelable(true).setOnDismissListener(Scrap_dispose.this).show();

            }else {finish();}
            }
        });
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("报废列表");
        Intent intent = getIntent();
        repairsId = intent.getStringExtra("scrapId");
        lv_poperty = (ListView) findViewById(R.id.repairs_list);
        lv_poperty.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                if (data.get(position).getCategory().equals("已上传附件")){
                    Intent intent1 = new Intent(Scrap_dispose.this,Scrap_ck.class);
                    intent1.putExtra("repairsId", repairsId);
                    intent1.putExtra("number", data.get(position).getCode_number());
                    intent1.putExtra("Section",data.get(position).getSection());
                    intent1.putExtra("Asset_name",data.get(position).getAsset_name());
                    intent1.putExtra("Model",data.get(position).getModel());
                    intent1.putExtra("remark",data.get(position).getRemark());
                    intent1.putExtra("assetId",data.get(position).getAssetId());
                    startActivity(intent1);
                }else {
                    Intent intent1 = new Intent(Scrap_dispose.this,Scrap_Data.class);
                   // Intent intent1 = new Intent(Scrap_dispose.this,Scrap_ck.class);
                    intent1.putExtra("repairsId", repairsId);
                    intent1.putExtra("number", data.get(position).getCode_number());
                    intent1.putExtra("Section",data.get(position).getSection());
                    intent1.putExtra("Asset_name",data.get(position).getAsset_name());
                    intent1.putExtra("Model",data.get(position).getModel());
                    intent1.putExtra("remark",data.get(position).getRemark());
                    intent1.putExtra("assetId",data.get(position).getAssetId());
                    startActivity(intent1);

                }


            }
        });
        lv_poperty.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int i, long id) {
                new AlertView(" 提示！", "是否删除", "取消",new String[]{"确定"}, null, Scrap_dispose.this, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){
                            upload(data.get(i).getCode_number());

                        }
                        if (position==-1){

                        }

                    }
                }).setCancelable(true).setOnDismissListener(Scrap_dispose.this).show();
                return true;
            }
        });
        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
        mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
        mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
        mWaveSwipeRefreshLayout.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener(){
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {//模拟3秒的加载过程
                    @Override
                    public void run() {
                        load();
                        //接下来可以刷新ListView
                    }
                }, 1200);


            }

        });
    }

    private void eliminate() {
        new Thread(){
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("scrapId",repairsId)
                            .add("source", Since_case.set().getSource())
                            .build();
                    Request request = new Request.Builder()
                            .url(eliminate_url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse_eliminate(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void showResponse_eliminate(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject json = new JSONObject(responseData);
                    if (json.getString("state").equals("1")){
                        finish();
                    }else finish();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void upload(final String code_number) {
        new Thread(){
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("scrapId",repairsId)
                            .add("source",Since_case.set().getSource())
                            .add("assetNumber",code_number)
                            .build();
                    Request request = new Request.Builder()
                            .url(url_up)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse_up(responseData);

                } catch (IOException e) {
                    e.printStackTrace();

                }


            }
        }.start();
    }

    private void showResponse_up(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject json = new JSONObject(responseData);
                    if (json.getString("state").equals("1")){
                        load();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void load() {
        new Thread(){
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("scrapId",repairsId)
                            .add("source",Since_case.set().getSource())
                            .build();
                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);

                } catch (IOException e) {
                    e.printStackTrace();

                }


            }
        }.start();
    }

    private void showResponse(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (responseData.equals("[]")){
                    Toast.makeText(Scrap_dispose.this,"无数据",Toast.LENGTH_SHORT).show();
                   // finish();
                }
                list.clear();
                data.clear();
                Bitmap bitmap =null;
                mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
                Gson gson = new Gson();
                List<Property_bean> userList = gson.fromJson(responseData, new TypeToken<List<Property_bean>>(){}.getType());
                String deptId,userId="";
                for(int i = 0;i < userList.size();i++){
                    String assetName = userList.get(i).getAssetName();
                    if(!userList.get(i).getDeptId().equals("")){
                    deptId= userList.get(i).getDeptId();}else {deptId = "闲置物品";}
                    String assetNumber =userList.get(i).getAssetNumber();
                    if(!userList.get(i).getUserId().equals("")){
                     userId=userList.get(i).getUserId();}else {userId="无人使用";}
                    String model = userList.get(i).getModel();
                    String type="";
                    if (userList.get(i).getStatus().equals("0")){
                        type="待上传附件";
                        status="待上传附件";
                    }
                    if (userList.get(i).getStatus().equals("1")){
                        type="已上传附件";
                        status="已上传附件";
                    }
                    if(userList.get(i).getStatus().equals("")){
                        type="待上传附件";
                        status="待上传附件";
                    }
                    String remark = userList.get(i).getDetail();
                    Since_case.set().setIsRemarks("原因");
                    String assetId=userList.get(i).getAssetId();
                    if (userList.get(i).getImage().equals("")){
                        /*InputStream is = getResources().openRawResource(R.mipmap.null_po);
                        bitmap = BitmapFactory.decodeStream(is);*/
                    }else {
                        byte [] input = Base64.decode(userList.get(i).getImage(), Base64.DEFAULT);
                        bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                    }
                    //刚刚重新新增一个加assetID的构造方法
                    data.add(new AddRepairs_bean(bitmap,assetName,deptId,assetNumber,userId,model,type,remark,"状态","",assetId));
                }
                Addrepairs_Adapter adapter_item = new Addrepairs_Adapter(Scrap_dispose.this,R.layout.input_adapter_item,data);
                lv_poperty.setAdapter(adapter_item);
            }
        });
    }

    @Override
    protected void onRestart() {
        load();
        super.onRestart();
    }
    @Override
    public void onDismiss(Object o) {
    }

    @Override
    public void onBackPressed() {
        if (status.equals("待上传附件")) {
            new AlertView(" 提示！", "退出后，未上传附件的将不申请报废", "取消", new String[]{"确定"}, null, Scrap_dispose.this, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    //取消：position=-1,确定 position=0
                    if (position == 0) {
                        eliminate();
                    }
                    if (position == -1) {
                    }
                }
            }).setCancelable(true).setOnDismissListener(Scrap_dispose.this).show();
        }
        else {finish();}
    }
}
